<template>
  <a-modal
    :destroyOnClose="true"
    :maskClosable="false"
    :open="visibleFlag"
    :title="form.relationId ? '编辑替代物料' : '添加替代物料'"
    :width="550"
    @cancel="onClose"
  >
    <a-form ref="formRef" :label-col="{ style: 'width: 100px; display: inline-block; vertical-align: inherit;' }" :model="form" :rules="rules">
      <a-form-item label="主物料" name="materialCode">
        <TableSelect
          v-model:modelValue="form.materialCode"
          :columns="[
            { title: '物料编号', dataIndex: 'materialCode', key: 'materialCode' },
            { title: '物料名称', dataIndex: 'materialName', key: 'materialName' },
            { title: '物料规格', dataIndex: 'materialSpec', key: 'materialSpec' },
            { title: '归属客户', dataIndex: 'belongCustomerAbbreviation', key: 'belongCustomerAbbreviation' },
          ]"
          :options="materialData"
          :placeholder="'输入物料编号/名称/规格'"
          @search="handleMaterialSearch"
          @select="handleMainMaterialSelect"
        />
      </a-form-item>
      <a-form-item label="替代物料" name="replacementMaterialCode">
        <TableSelect
          v-model:modelValue="form.replacementMaterialCode"
          :columns="[
            { title: '物料编号', dataIndex: 'materialCode', key: 'materialCode' },
            { title: '物料名称', dataIndex: 'materialName', key: 'materialName' },
            { title: '物料规格', dataIndex: 'materialSpec', key: 'materialSpec' },
            { title: '归属客户', dataIndex: 'belongCustomerAbbreviation', key: 'belongCustomerAbbreviation' },
          ]"
          :filterKey="'materialCode'"
          :mode="'multiple'"
          :options="materialData"
          :placeholder="'输入物料编号/名称/规格'"
          @search="handleMaterialSearch"
        />
      </a-form-item>

      <a-form-item label="循环替代" name="circleFlag">
        <a-checkbox v-model:checked="form.circleFlag" />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button :loading="loading" type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup>
  import { nextTick, reactive, ref } from 'vue';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { fixedReplacementMaterialApi } from '/@/api/business/basic/material/fixed-replacement-material-api.js';
  import { smartSentry } from '/@/lib/smart-sentry';
  import TableSelect from '/@/components/TableSelect/index.vue';
  import { materialInfoApi } from '/@/api/business/basic/material/material-info-api.js';

  const emits = defineEmits(['reloadList']);

  // ------------------------ 显示与隐藏 ------------------------
  const visibleFlag = ref(false);
  const loading = ref(false);

  // ------------------------ 表单 ------------------------
  const formRef = ref();

  const formDefault = {
    materialCode: undefined,
    replacementMaterialCode: [],
    circleFlag: true,
  };

  const form = reactive({ ...formDefault });

  const rules = {
    materialCode: [{ required: true, message: '请选择主物料' }],
    replacementMaterialCode: [
      { required: true, message: '请选择至少一个替代物料' },
      {
        validator: (_, value) => {
          if (value && value.includes(form.materialCode)) {
            return Promise.reject('替代物料不能包含主物料');
          }
          return Promise.resolve();
        },
      },
    ],
  };

  // ------------------------ 物料搜索 ------------------------
  const materialData = ref([]);

  const handleMaterialSearch = async (searchValue) => {
    try {
      const param = {
        keywords: searchValue,
        belongCustomer: form.customerCode,
        materialProperty: 'ROW',
      };
      const res = await materialInfoApi.searchTop10(param);
      materialData.value = res.data.map((item) => ({
        ...item,
        key: item.materialCode,
      }));
    } catch (error) {
      smartSentry.captureError(error);
      message.error('物料搜索失败');
    }
  };

  const handleMainMaterialSelect = (value) => {
    form.materialCode = value.record.materialCode;
  };

  // ------------------------ 表单操作 ------------------------
  const addFlag = ref(true);

  async function show(rowData) {
    Object.assign(form, formDefault);
    if (Object.prototype.hasOwnProperty.call(rowData, 'materialCode')) {
      addFlag.value = false;
      const res = await fixedReplacementMaterialApi.backShow(rowData.materialCode, rowData.circleFlag);
      const initialData = {
        ...res.data,
        replacementMaterialCode: res.data.replacementMaterialCode ? res.data.replacementMaterialCode.split(',') : [],
      };
      Object.assign(form, initialData);
    }

    visibleFlag.value = true;
    nextTick(() => {
      formRef.value?.clearValidate();
    });
  }

  function onClose() {
    visibleFlag.value = false;
    Object.assign(form, formDefault);
  }

  async function onSubmit() {
    try {
      await formRef.value.validateFields();

      if (form.replacementMaterialCode.length === 0) {
        message.warning('请至少选择一个替代物料');
        return;
      }

      loading.value = true;
      SmartLoading.show();

      const submitData = {
        ...form,
        replacementMaterialCode: form.replacementMaterialCode.join(','),
      };

      if (!addFlag.value) {
        await fixedReplacementMaterialApi.update(submitData);
        message.success('更新成功');
      } else {
        await fixedReplacementMaterialApi.add(submitData);
        message.success('添加成功');
      }

      emits('reloadList');
    } catch (error) {
      if (error.errorFields) {
        message.error('请完善表单信息');
      } else {
        smartSentry.captureError(error);
        message.error('操作失败');
      }
    } finally {
      onClose();
      loading.value = false;
      SmartLoading.hide();
    }
  }

  defineExpose({
    show,
  });
</script>
